"""
2022  B圈新版课程 | 邢不行
author: 邢不行
微信: xbx6660
"""
import base64
import hashlib
import hmac
import json
import time
from datetime import datetime
from urllib import parse

import requests

from 币安资金费率监控.config import *


def cal_timestamp_sign(secret):
    # 根据钉钉开发文档，修改推送消息的安全设置https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    # 也就是根据这个方法，不只是要有webhook，还要有secret
    # 当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
    # python3用int取整
    timestamp = int(round(time.time() * 1000))
    # 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
    secret_enc = bytes(secret.encode('utf-8'))
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign.encode('utf-8'))
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    # 得到最终的签名值
    sign = parse.quote_plus(base64.b64encode(hmac_code))
    return str(timestamp), str(sign)


def send_dingding_msg(content):
    try:
        msg = {
            "msgtype": "text",
            "text": {"content": datetime.now().strftime("%m-%d %H:%M:%S") + '\n' + content}
        }
        headers = {"Content-Type": "application/json;charset=utf-8"}
        # https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        timestamp, sign_str = cal_timestamp_sign(secret)
        url = 'https://oapi.dingtalk.com/robot/send?access_token=' + webhook + \
              '&timestamp=' + timestamp + '&sign=' + sign_str
        body = json.dumps(msg)
        requests.post(url, data=body, headers=headers, timeout=10)
        print('成功发送钉钉\n')
    except Exception as e:
        print(f"发送钉钉失败:{e}\n")


# 发送资金费率信息
def send_dingding_msg_for_funding_rate(df):
    dingding_msg = ''
    _ = str(df.at[0, 'nextFundingTime_GMT8']).split(' ')
    next_funding_time_GMT8 = _[0][5:] + ' ' + _[1][:-3] # 获取月日 时分
    dingding_msg += f'下次资金费率时间：\n{next_funding_time_GMT8}\n'
    df.rename(columns={'lastFundingRate': '资金费率', 'markPrice': '标记价格'}, inplace=True)
    for index, row in df.iterrows():
        dingding_msg += row[['symbol', '资金费率', '标记价格']].to_string() + '\n'
    send_dingding_msg(dingding_msg)
